# -*- coding: utf-8 -*-

from sys import *
path.append("tools/")
from Log import *
from PyQt4 import QtCore, QtSql, QtXml
from PyQt4.QtSql import *
from PyQt4.QtCore import *
from PyQt4.QtXml import *


class DBManager():
  def __init__(self, filename):
    self.xmlFile = QFile(filename)
    
    self.db = QSqlDatabase()
    if(self.parseFile() == True):
      if(self.db.open() == False):
	sqlLog.put(
	"Cannot open database. SQL answer :\n" +
	self.lastError() + "\n"
	"Check the db acces xml file.")
    else:
      lgdsLog.put("Error while parsing the xml file : " + 
      filename + ".\n Check syntax.")
      
  def isOpen(self):
    return self.db.isOpen()

  def close(self):
    self.db.close()

  def lastError(self):
    return self.db.lastError().databaseText()
    
  def parseFile(self):
    if(self.xmlFile.open(QIODevice.ReadOnly) == True):
      doc = QDomDocument()
      doc.setContent(self.xmlFile)
      self.xmlFile.close()
      root = doc.documentElement()
      nodeList = root.childNodes()
      for i in range(nodeList.count()):
	n = nodeList.at(i).toElement()
	if(n.nodeName() == "adapter"):
	  if(n.text() == "mysql"):
	    self.db = QSqlDatabase.addDatabase("QMYSQL")
	  elif(n.text() == "posgresql"):
	    self.db = QSqlDatabase.addDatabase("QPSQL")
	  else:
	    return False
	elif(n.nodeName() == "host"):
	  self.db.setHostName(n.text())
	elif(n.nodeName() == "name"):
	  self.db.setDatabaseName(n.text())
	elif(n.nodeName() == "user"):
	  self.db.setUserName(n.text())
	elif(n.nodeName() == "password"):
	  self.db.setPassword(n.text())
      return True
    return False
    
  def execQuery(self, query):
    q = QSqlQuery(query)
    while (q.next()):
      res = q.value(0).toString();
      sqlLog.put(res)
    sqlLog.put(self.lastError())